import json
import os
import pymysql
import pymssql
from DBUtils.PooledDB import PooledDB
from pymysql.cursors import DictCursor
from pymysql.constants import CLIENT

from  apilib.component import compManager , TComp

class TCompObj( TComp):
    def __init__(self):
        super().__init__()
        self.handlers={
            "setObj": self.setObj,
            "getObj": self.getObj
        }
    def compInit(self):
        try:
            pass
        except Exception as er:
            self.manager.log(er)
    def getObjFn(self , objKey ):
        res = ""
        try:
            fn = f"{self.compSettings['dataPath']}/{self.code}/objKey.json"
            fn = fn .replace( "{rootPath}",self.manager.rootPath)
            dirName = os.path.dirname(fn)
            if not os.path.exists(dirName):
                os.makedirs(dirName , 0x777)
            res = fn
        except Exception as er:
            self.manager.log(er)
        return res
    def setObj(self , objKey , obj):
        res = {
            "objKey": objKey
        }
        try:
            fn = self.getObjFn(objKey)
            with open(fn , 'w' , encoding='utf-8') as f :
                f.write(json.dumps(obj, ensure_ascii=False))
            res['success'] = os.path.exists(fn)
        except Exception as er:
            self.manager.log(er)
        return  res
    def getObj(self , objKey , defaultObj ={}):
        res =  defaultObj
        try:
            fn = self.getObjFn(objKey)
            if os.path.exists(fn):
                with open(fn , 'r' , encoding='utf-8') as f :
                    try:
                        res= json.loads(f.read())
                    except Exception as err:
                        self.manager.log(err)
        except Exception as er:
            self.manager.log(er)
        return  res

_settings = {
    "dataPath":"/datas/compIo"
}
compManager.registComponentType('TCompObj' , TCompObj , _settings)
